import { _decorator, Component, Node, Vec2, Vec3 } from 'cc';
import { Battle } from '../Battle';
import { EnEvent } from '../Common/const/EnEvent';
import { GameAPI } from '../Common/GameAPI';
import { ParabolaMovement } from './ParabolaMovement';
const { ccclass, property } = _decorator;

@ccclass('EnergyController')
export class EnergyController extends Component {

    @property(Number)
    private energyType: number = 1;

    private isPickedUp: boolean = false;
    private movement: ParabolaMovement = null;

    start() {
        this.node.setScale(new Vec3(0.6, 0.6, 0.6));
    }

    onDisable() {
        this.isPickedUp = false;
    }

    onEnable() {
        this.scheduleOnce(function () {
            this.isPickedUp = true;
        }.bind(this), 0.2);
    }

    OnMoveComplete() {
        GameAPI.FireGEvent(EnEvent.PlayerEnergyAdd, { type: this.energyType, num: 1 });
        this.node.destroy();
    }

    update(deltaTime: number) {
        if (this.isPickedUp) {
            const playerWorldPos = Battle.playerNode.parent.getWorldPosition();
            const distance = Vec2.distance(this.node.getWorldPosition(), playerWorldPos);
            if (distance <= 400) {
                this.isPickedUp = false;
                if (this.movement == null) {
                    this.movement = this.node.addComponent(ParabolaMovement);
                }
                this.movement.targetNode = Battle.playerNode.parent;
                this.node.setParent(Battle.ContentParent);
                this.movement.OnInit(this.OnMoveComplete.bind(this));
            }
        }
    }
}


